package com.mashibing.juc.c_003;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName T01_FineCoarseLock
 * @Description 同步代码块中的语句越少越好  锁细化
 * @Author xiongwei.wu
 * @Date 2021/7/1 11:22
 **/
public class T01_FineCoarseLock {
    private int count = 0;

    synchronized void m1() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        count++;

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    void m2() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /**
         * 业务线程中只有这行代码需要加synchronized时，就不应该给整个方法加synchronized
         * 采用这种及细粒度锁，可以时线程争用时间变短，从而提高效率
         */
        synchronized (this) {
            count++;
        }

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
